package xjtu.se.articlecommunity.admin.info;

import org.springframework.web.bind.annotation.*;
import xjtu.se.articlecommunity.admin.info.dto.Admin;
import xjtu.se.articlecommunity.admin.info.dto.CodeMap;
import xjtu.se.articlecommunity.common.*;
import xjtu.se.articlecommunity.common.dto.CurrentUser;

import javax.annotation.Resource;

@RestController
@RequestMapping("/admin/info")
public class InfoAPI {

    @Resource
    private InfoService infoService;

    @Resource
    private CommonService commonService;

    @Resource
    private CacheService cacheService;

    @Resource
    private MailService mailService;

    @Resource
    private SMSService smsService;

    @RequestMapping("")
    private Result getInfo(@RequestHeader("AToken") String token) {
        CurrentUser currentUser = TokenUtils.getUserInfo(token,commonService);

        return Result.success(infoService.getInfo(currentUser));
    }

    @RequestMapping("/getMailVerificationCode/{mail}")
    private Result getMailVerificationCode(@PathVariable String mail) {
        String code = mailService.sendCode(mail);
        cacheService.saveVerificationCode(mail, code);
        return Result.success();
    }

    @RequestMapping("/getTelVerificationCode/{tel}")
    private Result getTelVerificationCode(@PathVariable String tel) {
        String code = smsService.sendVerificationCode(tel);
        cacheService.saveVerificationCode(tel, code);
        return Result.success();
    }

    @RequestMapping("/checkUpdate")
    private Result checkUpdate(@RequestBody CodeMap codeMap) {
        System.out.println(123);
        String code = cacheService.findVerificationCode(codeMap.getNumber());
        System.out.println(456);
        if(code.equals(codeMap.getCode())){
            return Result.success();
        }
        return Result.fail(Result.ERR_CODE_BUSINESS, "验证码失效或错误！");
    }

    @RequestMapping("/updatePwd")
    private Result updatePwd(@RequestHeader("AToken") String token, @RequestBody Admin admin) {
        CurrentUser currentUser = TokenUtils.getUserInfo(token,commonService);
        admin.setU_id(currentUser.getU_id());
        infoService.updatePwd(admin);
        return Result.success();
    }

    @RequestMapping("/updateTel/{tel}")
    private Result updateTel(@RequestHeader("AToken") String token, @PathVariable String tel) {

        CurrentUser currentUser = TokenUtils.getUserInfo(token,commonService);
        Admin admin = new Admin(currentUser.getU_id(), null, null, tel, null);
        infoService.updateTel(admin);
        return Result.success();
    }

    @RequestMapping("/updateMail/{mail}")
    private Result updateMail(@RequestHeader("AToken") String token, @PathVariable String mail) {

        CurrentUser currentUser = TokenUtils.getUserInfo(token,commonService);
        Admin admin = new Admin(currentUser.getU_id(), null, null, null, mail);
        infoService.updateMail(admin);
        return Result.success();
    }
}
